package model

import (
	"server/tool"
)

type Role struct {
	BaseModel
	RoleName   string           `gorm:"unique;comment:'角色名称'";json:"role_name"`
	Permission []RolePermission `gorm:"FOREIGNKEY:role_id;ASSOCIATION_FOREIGNKEY:id;comment:'角色权限标识'";json:"role_permissions"`
}

var role Role
var roles []Role

func (e *Role) GetList(param tool.Pagination) ([]Role, error) {
	if param.KeyWords == "" {
		if err := GlobalDB.Limit(param.PageSize).Offset((param.PageNo - 1) * param.PageSize).Preload("Permission").Find(&roles).Error; err != nil {
			return roles, err
		}
	} else {
		if err := GlobalDB.Limit(param.PageSize).Offset((param.PageNo-1)*param.PageSize).Where("role_name like ?", "%"+param.KeyWords+"%").Preload("Permission").Find(&roles).Error; err != nil {
			return roles, err
		}
	}

	return roles, nil
}
func (e *Role) GetOne(id uint) (Role, error) {
	if err := GlobalDB.Where("id = ?", id).First(&role).Error; err != nil {
		return role, err
	}
	return role, nil
}
func (e *Role) Add(model Role) (Role, error) {
	err := GlobalDB.Create(&model).Preload("Permission").Error
	if err != nil {
		return role, err
	}
	return role, nil
}

// 角色表关联角色权限表 主子表关系，修改的时候需要清空子表数据在更新子表数据
func (e *Role) Edit(model Role) error {
	tx := GlobalDB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if tx.Error != nil {
		return tx.Error
	}
	if err := tx.Where("role_id = ?", int(model.ID)).Delete(RolePermission{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	if err := tx.Where("id = ?", int(model.ID)).Delete(Role{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	if err := tx.Create(&model).Preload("Permission").Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}
func (e *Role) Del(id uint) error {
	tx := GlobalDB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if tx.Error != nil {
		return tx.Error
	}
	if err := tx.Where("role_id = ?", id).Delete(RolePermission{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	if err := tx.Where("id = ?", id).Delete(Role{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	return tx.Commit().Error
}
